package com.speed_run.service.impl;

import com.speed_run.dto.*;
import com.speed_run.global.LoginType;
import com.speed_run.global.UserSession;
import com.speed_run.mapper.AlbumMapper;
import com.speed_run.mapper.AuthMapper;
import com.speed_run.mapper.CircleMapper;
import com.speed_run.mapper.UserMapper;
import com.speed_run.model.UserAuth;
import com.speed_run.model.UserInfo;
import com.speed_run.service.ICircleService;
import com.speed_run.service.IUserService;
import com.speed_run.utils.CommonUtils;
import com.speed_run.utils.ImageUtils;
import com.speed_run.utils.JwtUtils;
import com.speed_run.utils.ResponseEntity;
import com.speed_run.vo.*;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Log4j2
public class UserServiceImpl implements IUserService {

	@Autowired
	private UserMapper userMapper;

	@Autowired
	private AuthMapper authMapper;

	@Autowired
	private AlbumMapper albumMapper;
	
	@Autowired
	private CircleMapper circleMapper;
	
	@Value("${config.host}")
	private String host;

	@Autowired
	private ICircleService circleService;

	@Override
	public UserInfo getUserInfo(Long id) {
		return null;
	}

	/**
	 * 新增用户注册，目前只能通过手机号进行注册
	 * @param info
	 */
	@Override
	@Transactional
	public ResponseEntity addUserInfo(UserRegVo info) {
	    //checkSmsCode();
		int count = authMapper.getAuthByTelAuth(info.getTelephone());
		if(count != 0){
			return ResponseEntity.fail("当前账号已经被注册");
		}
		Map<String, String> data = new HashMap<String, String>();
		UserInfo userInfo = info.userInfo();
        userMapper.addUser(userInfo);
		UserAuth auth = info.authInfo(userInfo.getUserId(), LoginType.TEL);
		auth.setAuthId(info.getTelephone());
		auth.setAuthPwd(info.getPassword());
		authMapper.saveAuth(auth);
		data.put("token", JwtUtils.generateToken(userInfo.getUserId()));
		data.put("userId",userInfo.getUserId());
		return ResponseEntity.ok("注册成功",data);
	}

	/**
	 * 编辑和新增用户信息，目前在完善个人资料界面只有头像和昵称，其他自己字段作为扩展字段
	 * @param info
	 */
	@Override
	public void editUserInfo(UserInfo info) {

	}

	@Override
	@Transactional
	public ResponseEntity editUserInfo(UserInfoDTO info, MultipartFile file,  MultipartFile[] album) {
		String userId = JwtUtils.pareseToken(info.getToken());
		UserInfo userInfo = userMapper.getUserByUserId(userId);
		if(userInfo == null){
			return ResponseEntity.fail("当前用户不存在");
		}
		//更新用户信息
		userInfo = updateUserInfo(userInfo, info, file);
		userMapper.updateUserInfo(userInfo);
		//更新用户相册
		List<UserAlbumVo>  list = getUserAlbum(userId,album);
		if(!list.isEmpty()){
			albumMapper.saveAlbum(list);
		}
		if(!StringUtils.isEmpty(info.getDelAlbumIds())){
			List<Integer> ids = new ArrayList<>();
			for (String id: info.getDelAlbumIds().split(",")) {
				ids.add(Integer.valueOf(id));
			}
			albumMapper.delAlbum(ids);
		}
		if(!StringUtils.isEmpty(info.getOrd())){
			String[] ordArray =  info.getOrd().split(",");
			for (String ord:ordArray) {
				String[] _ord = ord.split(":");
				if(!StringUtils.isEmpty(_ord[0])&& !StringUtils.isEmpty(_ord[1])){
					albumMapper.updateOrd(Integer.valueOf(_ord[0]),Integer.valueOf(_ord[1]));
				}
			}
		}
		return ResponseEntity.ok("更新信息成功");
	}

	/**
	 * 用户编辑资料时，获取用户信息接口
	 * @param token
	 * @return
	 */
	@Override
	public ResponseEntity getUserInfo(String token) {
		String userId = JwtUtils.pareseToken(token);
		UserInfoVo vo =userMapper.getEditUserInfo(userId);
		if(vo.getAvator() != null && !vo.getAvator().equals("")){
			vo.setAvatorPre(host+vo.getAvator().substring(0,vo.getAvator().lastIndexOf("."))+"pre.jpg");
		}

		for (AlbumVo v: vo.getAlbums()) {
			String url = v.getUrl();
			String urlPre = "";
			if(url != null && !url.equals("")){
				urlPre= url.substring(0,url.lastIndexOf("."))+"pre.jpg";
				v.setUrl(host+v.getUrl());
				v.setUrlPre(host+urlPre);
			}
		}
		vo.setAvator(org.springframework.util.StringUtils.isEmpty(vo.getAvator())?"":host+vo.getAvator());
		return ResponseEntity.ok("获取用户信息成功",vo);
	}

	@Override
	public ResponseEntity modifyPwd(ModifyPwdVo vo) {
		//TODO checkSMScode();
		String userId = JwtUtils.pareseToken(vo.getToken());
		int count = authMapper.checkOldPwd(vo.getOldPwd(), userId);
		if(count == 0){
			return ResponseEntity.fail("旧密码输入错误");
		}
		authMapper.updatePwd(vo.getNewPwd(), userId);
		return ResponseEntity.ok("修改密码成功");
	}

	@Override
	public ResponseEntity forget(UserRegVo info) {
		//TODO checkSMScode
		if(authMapper.checkUserByTel(info.getTelephone()) == 0){
		   return ResponseEntity.fail("当前手机未注册");
		}else{
			authMapper.updatePwdByTel(info.getPassword(),info.getTelephone());
			return ResponseEntity.ok("修改密码成功");
		}
	}

	@Override
	public ResponseEntity getMyInfo(String token) {
		MyInfo info = new MyInfo();
		String userId = JwtUtils.pareseToken(token);
		UserInfoVo vo =userMapper.getEditUserInfo(userId);
		/*if(vo.getAvator() != null && vo.getAvator() != ""){
			vo.setAvatorPre(vo.getAvator().substring(0,vo.getAvator().lastIndexOf("."))+"pre.jpg");
		}*/
		for (AlbumVo v: vo.getAlbums()) {
			String url = v.getUrl();
			String urlPre = "";
			if(url != null && !url.equals("")){
				urlPre= url.substring(0,url.lastIndexOf("."))+"pre.jpg";
				v.setUrl(host+v.getUrl());
				v.setCanDeleted(true);
				v.setUrlPre(host+urlPre);
			}
		}
		info.setAvator(org.springframework.util.StringUtils.isEmpty(vo.getAvator())?"":host+vo.getAvator().substring(0,vo.getAvator().lastIndexOf("."))+"pre.jpg");
		info.setAlbums(vo.getAlbums());
		info.setCollect(0);
		info.setFollow(circleMapper.getMyFollow(userId).size()+circleMapper.getUserCircle(userId).size());
		info.setFollower(circleMapper.getMyFollowers(userId).size());
		info.setNickName(vo.getNickName());
		return ResponseEntity.ok("获取信息成功",info);
	}


	private List<UserAlbumVo> getUserAlbum(String userId, MultipartFile[] album) {
		String relativePath = null;
		String filepath = null;
		List<UserAlbumVo> list = new ArrayList<UserAlbumVo>();
		if(album.length == 0){
			return list;
		}
		Integer maxOrder = albumMapper.getAlbumCount(userId);
		if(maxOrder == null) {
			maxOrder = -1;
		}
		for(MultipartFile file :album) {
			if(maxOrder == 8)
				break;
			String fileName = file.getOriginalFilename().toLowerCase();
			relativePath = getAlbumRelativePath(fileName.substring(fileName.lastIndexOf(".")).split("\\.")[1]);
			filepath = getFilepath(relativePath);
			try {
				File avatorFile = new File(filepath);
				avatorFile.createNewFile();
				file.transferTo(avatorFile);

				String zipFilePath = filepath.substring(0,filepath.lastIndexOf("."));
				zipFilePath = zipFilePath + "pre.jpg";
				ImageUtils.reduceImg(filepath,zipFilePath,60,60,null);
			}catch (IOException E){
				log.error(E);
				continue;
			}
			UserAlbumVo vo = new UserAlbumVo();
			vo.setOrder(++maxOrder);
			vo.setUserId(userId);
			vo.setUrl(relativePath);
			list.add(vo);
		}
		return list;
	}



	private UserInfo updateUserInfo(UserInfo userInfo, UserInfoDTO info,MultipartFile  file) {
		if(file != null){
			try {
				String fileName = file.getOriginalFilename().toLowerCase();
				String relativePath = getRelativePath(fileName.substring(fileName.lastIndexOf(".")).split("\\.")[1]);
				String filepath = getFilepath(relativePath);
				String zipFilePath = filepath.substring(0,filepath.lastIndexOf("."));
				zipFilePath = zipFilePath + "pre.jpg";
				log.info("图片上传路径"+filepath);
				File avatorFile = new File(filepath);
				avatorFile.createNewFile();
				file.transferTo(avatorFile);
				ImageUtils.reduceImg(filepath,zipFilePath,60,60,null);
				userInfo.setAvator(relativePath);
			}catch (IOException e){
				e.printStackTrace();
			}
		}
		userInfo.setNickName(info.getNickName());
		userInfo.setHeight(info.getHeight());
		userInfo.setBirthday(info.getYear());
		userInfo.setAddress(info.getLocation());
		userInfo.setSex(info.getSex());
		userInfo.setWeight(info.getWeight());
		return userInfo;
	}

	private String getFilepath(String relativePath) {
		return this.getClass().getClassLoader().getResource("")
                .getPath().split("WEB-INF")[0]+ relativePath;
	}

	private String getRelativePath(String s) {
		return "img"+ File.separator+"avator"+File.separator +
                            CommonUtils.getPicName()+"."+ s;
	}

	private String getAlbumRelativePath(String s) {
		return "img"+ File.separator+"album"+File.separator +
				CommonUtils.getPicName()+"."+ s;
	}

	public static void main(String[] args) {
		String f = "E:\\123\\123\\123\\3.3.png";
		String zipf = f.substring(f.lastIndexOf("."));
		System.out.println(zipf);
	}



	@Override
	public ResponseEntity getUserIndex(String userId, Double lat,Double lng) {
		MyInfoDTO info = new MyInfoDTO();
		//String userId = UserSession.get().getUserId();
		UserInfoVo vo =userMapper.getEditUserInfo(userId);
		/*if(vo.getAvator() != null && vo.getAvator() != ""){
			vo.setAvatorPre(vo.getAvator().substring(0,vo.getAvator().lastIndexOf("."))+"pre.jpg");
		}*/
		for (AlbumVo v: vo.getAlbums()) {
			String url = v.getUrl();
			String urlPre = "";
			if(url != null && !url.equals("")){
				urlPre= url.substring(0,url.lastIndexOf("."))+"pre.jpg";
				v.setUrl(host+v.getUrl());
				v.setCanDeleted(userId.equals(UserSession.get().getUserId())?true:false);
				v.setUrlPre(host+urlPre);
			}
		}
		info.setAvator(org.springframework.util.StringUtils.isEmpty(vo.getAvator())?"":host+vo.getAvator().substring(0,vo.getAvator().lastIndexOf("."))+"pre.jpg");
		info.setAlbums(vo.getAlbums());
		info.setCollect(0);
		info.setFollow(circleMapper.getMyFollow(userId).size());
		info.setFollower(circleMapper.getMyFollowers(userId).size());
		info.setNickName(vo.getNickName());
		info.setAge(vo.getAge());
		info.setSex(vo.getSex());
		Integer num = userMapper.getFollowed(userId,UserSession.get().getUserId());
		if(num.equals(0)){
			info.setIsFollowed(false);
		}else {
			info.setIsFollowed(true);
		}
		UserIndexDTO dto = new UserIndexDTO();
		dto.setUserInfo(info);

		List<UserCircleDTO> moment= circleService.setMoments(null,userId, new IndexDTO(),lat,lng);
		dto.setMoment(moment);
		return ResponseEntity.ok("success",dto);
	}

	@Override
	public ResponseEntity deleteUserAlbum(String ids) {
		if(org.springframework.util.StringUtils.isEmpty(ids)){
			return ResponseEntity.ok("success");
		}
		String[] _ids = ids.split(",");
		List<Integer> idsList = new ArrayList<>();
		for(String id : _ids){
			idsList.add(Integer.valueOf(id));
		}
		albumMapper.delAlbum(idsList);
		return ResponseEntity.ok("success");
	}

}
